<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * Global error variable 
 */
$error_msg = array();

/**
 * Converts value to nonnegative integer.
 *
 * @param mixed $maybeint Data you wish to have convered to an nonnegative integer
 * @return int An nonnegative integer
 */
if ( !function_exists('absint') )
{
    function absint( $number ) 
    {
        return abs( intval( $number ) );
    }
}

/**
 * Serialize data, if needed.
 *
 * @param mixed $data Data that might be serialized.
 * @return mixed A scalar data
 */
if ( !function_exists('maybe_serialize') )
{
    function maybe_serialize( $data ) 
    {
        if ( is_array( $data ) || is_object( $data ) )
            return serialize( $data );
    
        if ( is_serialized( $data ) )
            return serialize( $data );
    
        return $data;
    }
}

/**
 * Unserialize value only if it was serialized.
 *
 *
 * @param string $original Maybe unserialized original, if is needed.
 * @return mixed Unserialized data can be any type.
 */
if ( !function_exists('maybe_unserialize') )
{
    function maybe_unserialize( $original ) 
    {
        if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
            return @unserialize( $original );
        return $original;
    }
}

/**
 * Check value to find if it was serialized.
 *
 * If $data is not an string, then returned value will always be false.
 * Serialized data is always a string.
 *
 *
 * @param mixed $data Value to check to see if was serialized.
 * @return bool False if not serialized and true if it was.
 */
if ( !function_exists('is_serialized') )
{
    function is_serialized( $data ) 
    {
        // if it isn't a string, it isn't serialized
        if ( ! is_string( $data ) )
            return false;
        $data = trim( $data );
        if ( 'N;' == $data )
            return true;
        $length = strlen( $data );
        if ( $length < 4 )
            return false;
        if ( ':' !== $data[1] )
            return false;
        $lastc = $data[$length-1];
        if ( ';' !== $lastc && '}' !== $lastc )
            return false;
        $token = $data[0];
        switch ( $token ) {
            case 's' :
                if ( '"' !== $data[$length-2] )
                        return false;
            case 'a' :
            case 'O' :
                return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
            case 'b' :
            case 'i' :
            case 'd' :
                return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
        }
        return false;
    }
}

/**
 * Check whether variable exist or not
 *
 * If current variable does not exist, return false then set default return value
 *
 * @param variable name, default value, default on set variable but empty
 * @return value if variable is set, false, or specified default value
 */
if ( !function_exists('ippi_isset') )
{
    function ippi_isset( &$val, $default=NULL, $default_on_empty=false )
    {
        if(isset($val))
            $tmp = ($default_on_empty && empty($val) ? $default : $val);
        else
            $tmp = $default;
        return $tmp;
    }
}

/**
 * get date of datetime.
 * @param variable date, default value, default on set variable but empty
 * @return string of date, false if date param is empty.
 */
if ( !function_exists('get_date') )
{
    function get_date($date='')
    {
        if(!$date) return false;
        
        $day    = date('d', strtotime($date));
        $month  = date('M', strtotime($date));
        $year   = date('y', strtotime($date));
        
        return '<span class="h2">' . $day . '</span><span>' . $month . ' ' . $year . '</span>';
    }
}

/**
 * get time of datetime.
 * @param variable date, default value, default on set variable but empty
 * @return string of time, false if date param is empty.
 */
if ( !function_exists('get_time') )
{
    function get_time($date='')
    {
        if(!$date) return false;
        
        $time   = date('h:i', strtotime($date));
        $format = date('A', strtotime($date));
        
        return $time . ' ' . $format;
    }
}

/**
 * Add a new option.
 *
 * You do not need to serialize values. If the value needs to be serialized, then
 * it will be serialized before it is inserted into the database. Remember,
 * resources can not be serialized or added as an option.
 *
 * You can create options without values and then add values later. Does not
 * check whether the option has already been added, but does check that you
 * aren't adding a protected WordPress option. Care should be taken to not name
 * options the same as the ones which are protected and to not add options
 * that were already added.
 *
 * @param string $option Name of option to add. Expected to not be SQL-escaped.
 * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped.
 * @param mixed $deprecated Optional. Description. Not used anymore.
 * @param bool $autoload Optional. Default is enabled. Whether to load the option when WordPress starts up.
 * @return null returns when finished.
 */
if ( !function_exists('add_option') )
{
    function add_option($option, $value = '')
    {
        $CI =& get_instance();
        
        $option = trim($option);
        if ( empty($option) ) return false;
        
        $value  = maybe_serialize( $value );
    
        $data   = array(
            'name'  => $option,
            'value' => $value,
        );
        
        $result = $CI->model_option->add_option($data);
    
        if ( $result ) return true;
    
        return false;
    }
}

/**
 * Retrieve option value based on name of option.
 *
 * If the option does not exist or does not have a value, then the return value
 * will be false. This is useful to check whether you need to install an option
 * and is commonly used during installation of plugin options and to test
 * whether upgrading is required.
 *
 * If the option was serialized then it will be unserialized when it is returned.
 *
 *
 * @param string $option Name of option to retrieve. Expected to not be SQL-escaped.
 * @return mixed Value set for the option.
 */
if ( !function_exists('get_option') )
{
    function get_option( $option, $default = false ) {
        $CI     =& get_instance();
        $option = trim($option);

        if ( empty($option) ) return false;
        $value  = array();

        $CI->db->select('value');
        $CI->db->where('name', $option);
        $CI->db->limit(1);
        
        $query  = $CI->db->get('tbl_options');
        $row    = $query->row();
        
        if ( is_object( $row ) ) {
            $value[$option] = $row->value;
        }

        return maybe_unserialize( $value[$option] );
    }
}

/**
 * Update the value of an option that was already added.
 *
 * You do not need to serialize values. If the value needs to be serialized, then
 * it will be serialized before it is inserted into the database. Remember,
 * resources can not be serialized or added as an option.
 *
 * If the option does not exist, then the option will be added with the option
 * value, but you will not be able to set whether it is autoloaded. If you want
 * to set whether an option is autoloaded, then you need to use the add_option().
 *
 * @param string $option Option name. Expected to not be SQL-escaped.
 * @param mixed $newvalue Option value. Expected to not be SQL-escaped.
 * @return bool False if value was not updated and true if value was updated.
 */
if ( !function_exists('update_option') ){
    function update_option( $option, $newvalue )
    {
        $CI =& get_instance();
    
        $option = trim($option);
        if ( empty($option) ) return false;
    
        if ( is_object($newvalue) )
            $newvalue = clone $newvalue;
    
        $newvalue   = sanitize_option( $option, $newvalue );
        $oldvalue   = get_option( $option );
    
        // If the new and old values are the same, no need to update.
        if ( $newvalue === $oldvalue )
            return false;
    
        if ( false === $oldvalue )
            return add_option( $option, $newvalue );
    
        $_newvalue  = $newvalue;
        $newvalue   = maybe_serialize( $newvalue );
    
        $data       = array('value' => $newvalue);
        $CI->db->where('name', $option);
    
        $result     = $CI->db->update('tbl_options', $data);
    
        if ( $result )
            return true;
    
        return false;
    }
}

/**
 * Sanitises various option values based on the nature of the option.
 *
 * This is basically a switch statement which will pass $value through a number
 * of functions depending on the $option.
 *
 * @param string $option The name of the option.
 * @param string $value The unsanitised value.
 * @return string Sanitized value.
 */
function sanitize_option($option='', $value='')
{
	$option = trim($option);
	
	if (empty($option))
	{
		return '';
	}
	
	if (is_string($value))
	{
		$value = trim($value);
	}
	
	switch ($option)
	{
		case 'admin_email':
			$value = sanitize_email($value);
			
			if (!is_email($value))
			{
				// Resets option to stored value in the case of failed sanitization
				$value = get_option($option);
			}
			
			break;
			
		case 'new_admin_email':
			$value = sanitize_email($value);
			
			if (!is_email($value))
			{
				// Resets option to stored value in the case of failed sanitization
				$value = get_option($option);
			}
			
			break;
			
		case 'thumbnail_size_w':
		case 'thumbnail_size_h':
		case 'medium_size_w':
		case 'medium_size_h':
		case 'large_size_w':
		case 'large_size_h':
		case 'mailserver_port':
		case 'users_can_register':
		case 'start_of_week':
			$value = absint($value);
			break;

		case 'date_format':
		case 'time_format':
		case 'mailserver_url':
		case 'mailserver_login':
		case 'mailserver_pass':
		case 'upload_path':
			$value = strip_tags($value);
			$value = addslashes($value);
			// calls stripslashes then addslashes
			$value = stripslashes($value);
			break;

		case 'gmt_offset':
			// strips slashes
			$value = preg_replace('/[^0-9:.-]/', '', $value);
			break;

		case 'timezone_string':
			$allowed_zones = timezone_identifiers_list();
			
			if (! in_array($value, $allowed_zones) && !empty($value))
			{
				// Resets option to stored value in the case of failed sanitization
				$value = get_option( $option );
			}
			
			break;

		default :
			$value = $value;
			break;
	}

	return $value;
}

/**
 * Retrieve event(s) num rows by day (date).
 * @param string $day Day (date) of event to retrieve. Expected to not be SQL-escaped.
 * @return mixed Value set for the event.
 */
if ( !function_exists('get_events_by_day') )
{
    function get_events_by_day( $day ) {
        $CI     =& get_instance();
        $day    = trim($day);

        if ( empty($day) ) return false;

        $CI->db->select('id_event');
        $CI->db->like('eventdate', $day, 'after');
        
        $query  = $CI->db->get('tbl_event');
        $num    = $query->num_rows();

        return $num;
    }
}

/**
 * Retrieve name of state, city and country.
 * @param int $id State, City or Country ID
 * @param strine $type Type of name that you will get
 * @return mixed Value set for the event.
 */
if ( !function_exists('get_name') )
{
    function get_name( $id, $type='' ) {
        $CI     =& get_instance();
        $name   = '';
        
        if ( !$id ) return false;
        $type   = trim($type);
        if ( empty($type) ) return false;
        
        switch($type){
            case 'city':
                $CI->db->select('city_name');
                $CI->db->where('city_id', $id);
                $query  = $CI->db->get('master_city');
                $row    = $query->row();
                $name   = $row->city_name;
                break;
            case 'country':
                $CI->db->select('country_name');
                $CI->db->where('country_id', $id);
                $query  = $CI->db->get('master_country');
                $row    = $query->row();
                $name   = $row->country_name;
                break;
            case 'state':
                $CI->db->select('state_name');
                $CI->db->where('state_id', $id);
                $query  = $CI->db->get('master_state');
                $row    = $query->row();
                $name   = $row->state_name;
                break;
        }
        
        return $name;
    }
}

/**
 * Retrieve last total rows found in database
 * Useful when we use limit database function
 * 
 * Ref: http://stackoverflow.com/questions/2439829/how-to-count-all-rows-when-using-select-with-limit-in-mysql-query
 * 
 * Please be careful when calls this function, make sure that the query executed before is the right one.
 * 
 * @author  Iqbal
 * @return  Integer
 */
if ( !function_exists('ippi_get_last_found_rows') )
{
    function ippi_get_last_found_rows(){
        $CI =& get_instance();
        
        $total_row  = 0;
        $query      = $CI->db->query('SELECT FOUND_ROWS() AS total_rows');
                    
        if($query && $query->num_rows())
            $total_row = $query->row()->total_rows;
        
        return $total_row;
    }
}

/**
 * Generate randon string
 * @author  Iqbal
 * @param   int     $length     Random String Length
 * @return  String
 */
if ( !function_exists('ippi_generate_rand_string') )
{
    function ippi_generate_rand_string($length = 0) {
        $characters     = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString   = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}

/**
 * Write any event to log table.
 * 
 * @author Iqbal
 * @param  string  $log_name        Log name
 * @param  string  $log_status      Log status
 * @param  string  $log_desc		Log description
 * @return void
 */
if ( !function_exists('ippi_log') )
{
    function ippi_log($log_name='',$log_status='',$log_desc='')
    {
    	$log_name = trim($log_name);
    	if (empty($log_name))
    	{
    		return false;
    	}
    	
    	$time  = date('Y-m-d H:i:s');
    	$ci    =& get_instance();
        
        $param = array($log_name, $time, $log_status, $log_desc);
        
    	$ci->db->query(
    		"INSERT INTO tbl_log(log_name,log_time,log_status,log_desc)" .
    		"VALUES(?, ?, ?, ?)", $param
    	);
    	
    	return true;
    }
}

/**
 * Strips out all characters that are not allowable in an email.
 *
 * @param string $email Email address to filter.
 * @return string Filtered email address.
 */
if ( !function_exists('sanitize_email') )
{
    function sanitize_email($email='')
    {
    	// Test for the minimum length the email can be
    	if (strlen( $email ) < 3)
    	{
    		return '';
    	}
    
    	// Test for an @ character after the first position
    	if (strpos($email, '@', 1) === false)
    	{
    		return '';
    	}
    
    	// Split out the local and domain parts
    	list($local, $domain) = explode('@', $email, 2);
    
    	// LOCAL PART
    	// Test for invalid characters
    	$local = preg_replace('/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local);
    	if ('' === $local)
    	{
    		return '';
    	}
    
    	// DOMAIN PART
    	// Test for sequences of periods
    	$domain = preg_replace('/\.{2,}/', '', $domain);
    	if ('' === $domain)
    	{
    		return '';
    	}
    
    	// Test for leading and trailing periods and whitespace
    	$domain = trim($domain, " \t\n\r\0\x0B.");
    	if ('' === $domain)
    	{
    		return '';
    	}
    
    	// Split the domain into subs
    	$subs = explode('.', $domain);
    
    	// Assume the domain will have at least two subs
    	if (2 > count($subs))
    	{
    		return '';
    	}
    
    	// Create an array that will contain valid subs
    	$new_subs = array();
    
    	// Loop through each sub
    	foreach ($subs as $sub)
    	{
    		// Test for leading and trailing hyphens
    		$sub = trim($sub, " \t\n\r\0\x0B-");
    		
    		// Test for invalid characters
    		$sub = preg_replace('/[^a-z0-9-]+/i', '', $sub);
    
    		// If there's anything left, add it to the valid subs
    		if ('' !== $sub)
    		{
    			$new_subs[] = $sub;
    		}
    	}
    	
    	// If there aren't 2 or more valid subs
    	if (2 > count($new_subs))
    	{
    		return '';
    	}
    	
    	// Join valid subs into the new domain
    	$domain = join('.', $new_subs);
    	
    	// Put the email back together
    	$email = $local . '@' . $domain;
    	
    	// Congratulations your email made it!
    	return $email;
    }
}

/**
 * Get full current URL
 * @param none
 * @return String
 */
if ( !function_exists('get_full_current_url') )
{
    function get_full_current_url() {
    	 if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) {
            $_SERVER['HTTPS'] = 'on';
            $_SERVER['SERVER_PORT'] = '443';
        }
    	 
    	$pageURL = 'http';
     	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
     	
     	$pageURL .= "://";
     	if ($_SERVER["SERVER_PORT"] != "80") {
      		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
     	} else {
      		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
     	}
     	
     	return $pageURL;
    }
}

/**
* Determine if SSL is used.
*
* @return bool True if SSL, false if not used.
*/
if ( !function_exists('is_ssl') ){
    function is_ssl() {
        // modified by Mr. Adi on 2012-10-18
        if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) {
            $_SERVER['HTTPS'] = 'on';
            $_SERVER['SERVER_PORT'] = '443';
        }
        
        if ( isset($_SERVER['HTTPS']) ) {
            if ( 'on' == strtolower($_SERVER['HTTPS']) )
                return true;
            if ( '1' == $_SERVER['HTTPS'] )
                return true;
        } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
            return true;
        }
        return false;
    }
}

/**
 * GET JNE City function.
 * 
 * @param[in] string $query City search
 * @param[in] string $type  Type search
 * 
 * @return AJAX String
 */
if ( !function_exists('get_city') ){
    function get_city($query='', $type='origin')
    {
        require_once (APPPATH . 'libraries/REST_Ongkir.php');
        
        $rest   = new REST_Ongkir(array('server' => 'http://api.ongkir.info/'));
        $result = $rest->post('city/list', array(
            'query' 	=> $query, 
            'type' 	    => $type,
            'courier' 	=> 'jne',
            'API-Key' 	=> '3b30a578296973010599603d711a3026'
        ), 'JSON');
        
        try
        {
            $status = $result['status'];
            
            if ($status->code == 0)
            {
                return $result['cities'];
            }
            else
            {
                echo 'Tidak ditemukan kota yang diawali ' + $query;	
            }
            
        }
        catch (Exception $e)
        {
            echo 'Processing error.';
        }
    }
}
    
/**
 * GET JNE Cost function.
 * 
 * @param[in] string $from      From City
 * @param[in] string $to        Destination City
 * @param[in] string $weight    Weight of Products
 * 
 * @return AJAX String
 */
if ( !function_exists('get_cost') ){
    function get_cost($from='', $to='', $weight=0)
    {
        require_once (APPPATH . 'libraries/REST_Ongkir.php');
        
        $rest = new REST_Ongkir(array('server' => 'http://api.ongkir.info/'));
        
        //ganti API-Key dibawah ini sesuai dengan API Key yang anda peroleh setalah mendaftar di ongkir.info
        $result = $rest->post('cost/find', array(
            'from'      => $from,
            'to'        => $to,
            'weight'    => $weight . '000',
            'courier'   => 'jne',
            'API-Key'   => '3b30a578296973010599603d711a3026'
        ));
        
        try
        {
            $status = $result['status'];
            
            if ($status->code == 0)
            {
                $prices = $result['price'];
                $city   = $result['city'];
                
                //echo "<pre>";
                //print_r($prices);
                //die();
                
                echo 'Ongkos kirim dari ' . $city->origin . ' ke ' . $city->destination . '<br /><br />';
                
                foreach ($prices->item as $item)
                {
                    echo 'Layanan: ' . $item->service . ', dengan harga : Rp. ' . $item->value . ',- <br />';
                }
            }
            else
            {
                echo 'Tidak ditemukan jalur pengiriman dari surabaya ke jakarta';
            }
        }
        catch (Exception $e)
        {
            echo 'Processing error.';
        }
    }
}

/*
CHANGELOG
---------
Insert new changelog at the top of the list.
-----------------------------------------------
Version YYYY/MM/DD  Person Name     Description
-----------------------------------------------
1.0.0   2014/07/02  Iqbal           - Create this changelog.
*/